package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.vo.TravelStatisVO;
import cn.wolfcode.wolf2w.redis.IRedisStatisService;
import cn.wolfcode.wolf2w.redis.IRedisTravelStatisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DateUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class RedisStatisTravelServiceImpl implements IRedisTravelStatisService {

    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ITravelService travelService;

    @Override
    public TravelStatisVO getStatisVo(String tid) {
        String key = RedisKeys.TRAVEL_STATIS_VO.join(tid);
        TravelStatisVO statisVO = null;
        //如果有值则说明存在对象
        if(template.hasKey(key)){
            String value = template.opsForValue().get(key);
            statisVO = JSON.parseObject(value, TravelStatisVO.class);
        }else{
            //没有对象;
            //先初始化对象
            statisVO = new TravelStatisVO();
            Travel travel = travelService.get(tid);
            BeanUtils.copyProperties(travel,statisVO);
            statisVO.setTravelId(travel.getId());
        }
        return statisVO;
    }

    @Override
    public void setStatisVo(TravelStatisVO vo) {
        String key = RedisKeys.TRAVEL_STATIS_VO.join(vo.getTravelId());
        template.opsForValue().set(key, JSON.toJSONString(vo));
    }

    @Override
    public void addViewnum(String tid) {
        //获取vo对象
        TravelStatisVO vo = this.getStatisVo(tid);
        vo.setViewnum(vo.getViewnum()+1);
        this.setStatisVo(vo);
    }

    @Override
    public Boolean travelThumbup(String tid, String id) {
        String key = RedisKeys.TRAVEL_THUMBUP_VO.join(id, tid);
        //判断是否有key,如果有则说明已经点赞过
        if(template.hasKey(key)){
            return false;
        }
        //没有则说明没有点赞
        TravelStatisVO vo = this.getStatisVo(tid);
        vo.setThumbsupnum(vo.getThumbsupnum()+1);
        this.setStatisVo(vo);
        //创建对象
        Date date = new Date();
        Date endDate = DateUtil.getEndDate(date);
        long time = DateUtil.getDateBetween(date, endDate);
        template.opsForValue().set(key,"1",time,TimeUnit.SECONDS);
        return true;
    }
}
